<?php

declare(strict_types=1);

namespace App\Controller\Home\Drp;


use App\Model\Bill;
use App\Model\Device;
use App\Model\DistributorDevice;
use App\Model\Order;
use App\Model\Station;
use Carbon\Carbon;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use App\Controller\AbstractController;
use App\Model\Distributors;

class HomeProfitController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected DistributorDevice $distributorDevice;

    #[Inject]
    protected Bill $bill;

    #[Inject]
    protected Order $order;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**盈利额
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getProfit(RequestInterface $request):ResponseInterface{
        try {
            $info = $this->distributors->getInfo($request);
            $data['all'] = $this->distributorDevice->where('distributor_id',$info['id'])
                ->sum('profit');
            $today = date('Y-m-d',time());
            $data['today'] = $this->bill
                ->where('created_at','>=',$today.' 00:00:00')
                ->where('created_at','<=',$today.' 23:59:59')
                ->where('account_type',1)
                ->where('account_id',$info['id'])
                ->sum('fee');
            $data['today'] = round($data['today'],2);
            return $this->success($data);
        } catch (\Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(code: '400', msg: $e->getMessage());
        }
    }

    public function insideProfit(RequestInterface $request):ResponseInterface{
        try {
            $info = $this->distributors->getInfo($request);
            if(!$info){
                return $this->error(code:'400',msg:'登录态失效 请重新登录');
            }
            if($info['level'] == 1){
                $devices = Device::where('distributor_id',$info['id'])
                    ->get(['id']);
            }else{
                $devices = Device::where('child_distributor_id',$info['id'])
                    ->get(['id']);
            }
            $indDevices = [];
            foreach($devices as $v){
                $indDevices[] =$v['id'];
            }
            $params = $request->inputs(['start','end']);
            $status = [Order::STATUS_END,Order::STATUS_REFUNDED];
            if(array_key_exists('start',$params) && $params['start']){
                if($info['level'] == 1){
                    $todayPower = Order::where('stop_at','>=',$params['start'].' 00:00:00')
                        ->where('stop_at','<=',$params['end'].' 23:59:59')
                        ->whereIn('device_id',$indDevices)
                        ->whereIn('status',$status)
                        ->sum('fee');
                    $data['today_income'] =  $todayPower;
                    $todayReturn = Order::where('stop_at','>=',$params['start'].' 00:00:00')
                        ->where('stop_at','<=',$params['end'].' 23:59:59')
                        ->whereIn('device_id',$indDevices)
                        ->sum('return_fee');
                    $data['today_refund'] =  $todayReturn;
                    $data['today'] =  sprintf("%.2f",$todayPower-$todayReturn);
                }else{
                    $todayPower = Order::where('stop_at','>=',$params['start'].' 00:00:00')
                        ->where('stop_at','<=',$params['end'].' 23:59:59')
                        ->whereIn('device_id',$indDevices)
                        ->whereIn('status',$status)
                        ->sum('fee');
                    $data['today_income'] =  $todayPower;
                    $todayReturn = Order::where('stop_at','>=',$params['start'].' 00:00:00')
                        ->where('stop_at','<=',$params['end'].' 23:59:59')
                        ->whereIn('device_id',$indDevices)
                        ->sum('return_fee');
                    $data['today_refund'] =  $todayReturn;
                    $data['today'] =  sprintf("%.2f",$todayPower-$todayReturn);
                }
            }else{
                $today = date('Y-m-d',time());
                if($info['level'] == 1){
                    $todayPower = Order::where('stop_at','>=',$today.' 00:00:00')
                        ->where('stop_at','<=',$today.' 23:59:59')
                        ->whereIn('device_id',$indDevices)
                        ->whereIn('status',$status)
                        ->sum('fee');
                    $data['today_income'] =  $todayPower;
                    $todayReturn = Order::where('stop_at','>=',$today.' 00:00:00')
                        ->where('stop_at','<=',$today.' 23:59:59')
                        ->whereIn('device_id',$indDevices)
                        ->sum('return_fee');
                    $data['today_refund'] =  $todayReturn;
                    $data['today'] =  sprintf("%.2f",$todayPower-$todayReturn);
                }else{
                    $todayPower = Order::where('stop_at','>=',$today.' 00:00:00')
                        ->where('stop_at','<=',$today.' 23:59:59')
                        ->whereIn('device_id',$indDevices)
                        ->whereIn('status',$status)
                        ->sum('fee');
                    $data['today_income'] =  round($todayPower,2);
                    $todayReturn = Order::where('stop_at','>=',$today.' 00:00:00')
                        ->where('stop_at','<=',$today.' 23:59:59')
                        ->whereIn('device_id',$indDevices)
                        ->sum('return_fee');
                    $data['today_refund'] =  $todayReturn;
                    $data['today'] =  sprintf("%.2f",$todayPower-$todayReturn);
                }
            }
            return $this->success($data);
        } catch (\Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(code: '400', msg: $e->getMessage());
        }
    }

    /**营业额
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function orderProfit(RequestInterface $request):ResponseInterface{
        try {
            $info = $this->distributors->getInfo($request);
            if(!$info){
                return $this->error(code:'400',msg:'登录态失效 请重新登录');
            }
            $class_id = $request->input('class_id');

            if(!$class_id){
                $query=$this->order->where('stop_at','>=',date('Y-m-d',time()).' 00:00:00')
                    ->where('stop_at','<=',date('Y-m-d',time()).' 23:59:59')
                    ->where('distributor_id',$info['id'])
                    ->where ('status',Order::STATUS_END);
            }else{
                if(!is_array($class_id)){
                    $class_id = json_decode($class_id,true);
                }
                $stations = Station::whereIn('class_id',$class_id)
                    ->pluck('id')->toArray();
                if(!$stations){
                    $stations = [];
                }
                $query = $this->order->where('stop_at','>=',date('Y-m-d',time()).' 00:00:00')
                    ->where('stop_at','<=',date('Y-m-d',time()).' 23:59:59')
                    ->whereIn('station_id',$stations)
                    ->where('status',Order::STATUS_END);
            }
            $data['count'] = $query->count();
            $result = $query->selectRaw('SUM(fee) as total_fee, SUM(return_fee) as total_return_fee,SUM(service_fee) as total_service_fee')->first();
            $data['today_income'] = $result->total_fee-$result->total_service_fee ?? 0;
            $data['today_refund'] = $result->total_return_fee ?? 0;
            $data['today'] = sprintf("%.2f", ($data['today_income'] ?? 0) - ($data['today_refund'] ?? 0));
            $data['rate'] = $info['rate'];
            $data['profit'] = 0;
            if($data['today']*$data['rate']){
                $data['profit'] = sprintf("%.2f", $data['today']*$data['rate']/100);
            }
            return $this->success($data);
        } catch (\Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(code: '400', msg: $e->getMessage());
        }
    }

    /**折线图数据
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getCharts(RequestInterface $request):ResponseInterface{
        try {
            $info = $this->distributors->getInfo($request);
            if(!$info){
                return $this->error(code:'400',msg:'登录态失效 请重新登录');
            }
            $endDate = Carbon::now();  // 当前日期时间
            $startDate = $endDate->copy()->subDays(14);  // 最近十五天的起始日期
            $dates = [];
            $data = [];
            while ($startDate->lte($endDate)) {
                $nowDay =  $startDate->toDateString();
                $dates[] = $nowDay;
                $data['date'][] = date('m/d',strtotime($nowDay));
                $startDate->addDay();
            }
            foreach($dates as $k => $v){
                $data['list'][] = $this->bill
                    ->where('created_at','>=',$v.' 00:00:00')
                    ->where('created_at','<=',$v.' 23:59:59')
                    ->where('account_type','App\Model\Distributors')
                    ->where('account_id',$info['id'])
                    ->where('type',$this->bill::TYPE_ORDER_PAY)
                    ->sum('fee');
            }
            return $this->success($data);
        } catch (\Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(code: '400', msg: $e->getMessage());
        }
    }

    /**营业额折线图
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function orderCharts(RequestInterface $request):ResponseInterface{
        try {
            $info = $this->distributors->getInfo($request);
            if(!$info){
                return $this->error(code:'400',msg:'登录态失效 请重新登录');
            }
            $class_id = $request->input('class_id');
            if(!$class_id){
                $stations = Station::where('class_id',$class_id)
                    ->pluck('id')->toArray();
                if(!$stations){
                    $stations = [];
                }
            }
            $endDate = Carbon::now();  // 当前日期时间
            $startDate = $endDate->copy()->subDays(14);  // 最近十五天的起始日期
            $dates = [];
            $data = [];
            while ($startDate->lte($endDate)) {
                $nowDay =  $startDate->toDateString();
                $dates[] = $nowDay;
                $data['date'][] = date('m/d',strtotime($nowDay));
                $startDate->addDay();
            }
            foreach($dates as $k => $v){
                if($class_id){
                    $result = Order::where('created_at','>=',$v.' 00:00:00')
                        ->where('created_at','<=',$v.' 23:59:59')
                        ->whereIn('station_id',$stations)
                        ->where('status',Order::STATUS_END)
                        ->selectRaw('SUM(fee - service_fee - return_fee) as net_income')
                        ->first();
                }else{
                    $result = Order::where('created_at','>=',$v.' 00:00:00')
                        ->where('created_at','<=',$v.' 23:59:59')
                        ->where('distributor_id',$info['id'])
                        ->where('status',Order::STATUS_END)
                        ->selectRaw('SUM(fee - service_fee - return_fee) as net_income')
                        ->first();
                }
                $data['list'][] = sprintf("%.2f", $result->net_income ?? 0);
            }

            return $this->success($data);
        } catch (\Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(code: '400', msg: $e->getMessage());
        }
    }

}
